
from stockanalyzer import *



# exponential moving average
def mea(dataList, interval):
    meaList = []
    lastAv = None
    interval = interval * 1.0
    previousWeight = (interval-1)/(interval+1)
    currentWeight = 2/(interval+1)

    for data in dataList:
        if not lastAv:
            lastAv = data
        else:
            lastAv = lastAv*previousWeight + data*currentWeight
        meaList.append(lastAv)
    return meaList

def stockMea(symbol, interval=26, start=None, stop=None):
    if not symbol:
        return []
    symbol = symbol.upper()

    interval = int(interval)
    if interval < 1:
        return []

    historicalData = getLocalHistorical(symbol, start=start, stop=stop)

    dateList = [dailyData['date'] for dailyData in historicalData]
    adjCloseList = [dailyData['adjClose'] for dailyData in historicalData]

    adjCloseMea = mea(adjCloseList, interval)

    return dateList, adjCloseMea


# moving average convergence/divergence
def macd(dataListFast, dataListSlow):
    macdList = []
    for fast, slow in zip(dataListFast, dataListSlow):
        macdList.append(fast - slow)
    return macdList

def stockMacd(symbol, fast=12, slow=26, start=None, stop=None):
    dateList, meaFast = stockMea(symbol, fast, start, stop)
    _, meaSlow = stockMea(symbol, slow, start, stop)

    macd = []
    adjCloseMacd = macd(meaFast, meaSlow)

    return dateList, adjCloseMacd

# ema of macd
def stockMacdEma(symbol, interval=9, fast=12, slow=26, start=None, stop=None):
    dateList, stockMacdValues = stockMacd(symbol, fast, slow, start, stop)
    macdEmaValues = mea(stockMacdValues, interval)
    return dateList, macdEmaValues










